<template>
  <div class="room-search">
    <template v-for="(tag, index) in tags">
      <a-tag :key="tag" :closable="true" @close="() => handleClose(tag)">
        <a-button type="link" v-on:click="$emit('click-tag', tag.value)">{{ tag.text }}</a-button>
      </a-tag>
    </template>
    <a-divider />
    <a-select
      show-search
      :value="value"
      placeholder="search room"
      style="width: 100%"
      :default-active-first-option="false"
      :show-arrow="false"
      :filter-option="false"
      :not-found-content="null"
      @search="handleSearch"
      @change="handleChange"
      v-on="$listeners"
    >
      <a-select-option v-for="d in data" :key="d.value" :disabled="d.disabled">{{ d.text }}</a-select-option>
    </a-select>
  </div>
</template>
<script>
import axios from "axios";
import querystring from "querystring";
const { remote } = window.require("electron");

const request = remote.require("request");
const Store = remote.require("electron-store");

const store = new Store();
let timeout;
let currentValue;

function fetch(value, callback) {
  if (timeout) {
    clearTimeout(timeout);
    timeout = null;
  }
  currentValue = value;

  function fake() {
    const str = querystring.encode({
      kw: value
    });
    let url = `https://www.douyu.com/japi/search/api/getSearchRec?${str}`;
    request(
      {
        url: url
      },
      function(error, response, body) {
        if (!error && response.statusCode == 200) {
          const result = JSON.parse(body).data.roomResult;
          const data = [];
          result.forEach(r => {
            data.push({
              value: r.rid,
              text: r.nickName,
              disabled: r.isLive !== 1
            });
          });
          callback(data);
        }
      }
    );
  }

  timeout = setTimeout(fake, 300);
}

function addTag(tags, value) {
  let tagList = tags;
  if (value && tagList.indexOf(value) === -1) {
    tagList = [...tagList, value];
  }
  console.log(tagList);
  store.set("tags", JSON.stringify(tagList));
  return tagList;
}

export default {
  data() {
    return {
      data: [],
      value: undefined,
      tags: []
    };
  },
  mounted() {
    this.tags = JSON.parse(store.get("tags"));
  },
  methods: {
    handleSearch(value) {
      fetch(value, data => (this.data = data));
    },
    handleChange(value) {
      this.value = value;
      fetch(value, data => {
        this.data = data;
        this.tags = addTag(this.tags, data[0]);
      });
    },
    handleClose(removedTag) {
      const tags = this.tags.filter(tag => tag !== removedTag);
      console.log(tags);
      this.tags = tags;
      store.set("tags", JSON.stringify(tags));
    }
  }
};
</script>
